import './logger.js';

import { cpuUsage, mem } from './index.js';

import WebSocket from 'ws';
import _ from 'lodash';
import { v4 as uuid } from 'uuid';

/**
 * State
 */
const state = {
    /**
     * 消息回调
     */
    onMessage: [],
    /**
     * WebSocket 实例
     */
    ws: undefined,
    /**
     * WebSocket 心跳定时器
     */
    wsHeartbeatTimer: undefined,
    /**
     * WebSocket 重连定时器
     */
    wsReconnectTimer: undefined,
};

/**
 * 初始化 WebSocket
 */
export const initWs = () => {
    // 连接已经建立
    if (state.ws?.readyState === 1) return;

    // 建立连接
    state.ws = new WebSocket(process.env.WSS);

    state.ws.onclose = (e) => {
        console.log('%cWebSocket 连接关闭！' + new Date().toLocaleString() + '：' + e.reason, 'color: red;');
        clearInterval(state.wsHeartbeatTimer);
        clearInterval(state.wsReconnectTimer);
        if (e.reason !== 'over') {
            state.wsReconnectTimer = setTimeout(() => {
                initWs();
            }, 10 * 1000);
        }
    };

    state.ws.onerror = () => {
        console.log('%cWebSocket 连接错误！' + new Date().toLocaleString(), 'color: red;');

        // state.wsReconnectTimer = setTimeout(() => {
        //     initWs();
        // }, 10 * 1000);
    };

    state.ws.onmessage = (e) => {
        // 心跳
        if (e.data === 'pong') return;

        _.forEach(state.onMessage, (callback) => {
            if (_.isFunction(callback)) {
                callback(e.data);
            }
        });
    };

    state.ws.onopen = () => {
        console.log('%cWebSocket 连接成功！' + new Date().toLocaleString(), 'color: green;');
        state.wsHeartbeatTimer = setInterval(async () => {
            if (state.ws?.readyState !== 1) return;
            const message = {
                id: uuid(),
                type: 'heartbeat',
                timestamp: +new Date(),
                cpu: 10, // CPU 使用率
                mem: 10, // 内存使用率
            };
            state.ws?.send(JSON.stringify(message));
        }, 30 * 1000);
    };
};

/**
 * 关闭 WebSocket
 */
export const closeWs = () => {
    clearInterval(state.wsHeartbeatTimer);
    clearInterval(state.wsReconnectTimer);

    state.ws?.close(1000, 'over');
};

/**
 * 连接关闭
 */
export const onClose = () => {
    console.log('onClose :>> ', 123);
};

/**
 * 连接错误
 */
export const onError = () => {
    console.log('onError :>> ', 123);
};

/**
 * 收到消息
 */
export const onMessage = (callback) => {
    state.onMessage.push(callback);
};

/**
 * 连接建立
 */
export const onOpen = () => {
    console.log('onOpen :>> ', 123);
};

/**
 * 发送消息
 */
export const sendMessage = (string) => {
    console.log('sendMessage :>> ', string);
    state.ws?.send(string);
};
